﻿Option Explicit On
Imports Microsoft.VisualBasic
Imports System
Imports System.Xml
Imports System.Data
Imports System.IO
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlClient

Public Class ClassStock

    Public Function CheckLimitStock(ByVal productid As String, ByVal amount As Decimal, ByRef conn As SqlConnection, ByRef tran As SqlTransaction) As Boolean
        Dim sql As String = "Select Op_ProductID,Op_ProductName,Op_ProductUnit,Op_ProductLimit,Op_ProductAmount From Op_Product Where Op_ProductID='" & productid & "'"
        Dim da As New SqlClient.SqlDataAdapter(sql, conn)
        Dim ds As New DataSet

        da.Fill(ds, "Limit")
        If ds.Tables("Limit").Rows.Count > 0 Then
            If amount >= ds.Tables("Limit").Rows(0).Item("Op_ProductLimit") Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If


    End Function
    Public Function DiscardStock(ByVal productid As String, ByVal amount As Decimal, ByVal Type As String, ByVal conn As SqlConnection, ByVal tran As SqlTransaction) As Boolean
        If CheckLimitStock(productid, amount, conn, tran) = False Then
            Return False
            Exit Function
        End If


        If Type = "1" Then
            amount += GetAmount(productid, conn, tran)
        End If

        If Type = "0" Then
            amount = GetAmount(productid, conn, tran) - amount

        End If



        Try
            If CheckLimitStock(productid, amount, conn, tran) = False Then
                Return False
                Exit Function
            End If

            Dim sql As String = "UPDATE Op_Product SET Op_ProductAmount=" & amount & " Where Op_ProductID='" & productid & "'"
            conn.Open()
            Dim cm As New SqlCommand(sql, conn)
            cm.ExecuteNonQuery()
            conn.Close()

        Catch ex As Exception
            Return False
            Exit Function
        End Try

        Return True
    End Function
    Public Function GetAmount(ByVal productid As String, ByVal conn As SqlConnection, ByVal tran As SqlTransaction) As Decimal
        Dim sql As String = "Select Op_ProductID,Op_ProductName,Op_ProductUnit,Op_ProductLimit,Op_ProductAmount From Op_Product Where Op_ProductID='" & productid & "'"
        Dim da As New SqlClient.SqlDataAdapter(sql, conn)
        Dim ds As New DataSet
        da.Fill(ds)
        Dim ReAmount As Decimal = 0.0
        ReAmount = ds.Tables(0).Rows(0).Item("Op_ProductAmount")
        Return ReAmount
    End Function

End Class
